﻿using System.Collections.Generic;
using System.Linq;
using PhotoBlogApp.Models.Builders;
using PhotoBlogApp.Models.ClientModels;

namespace PhotoBlogApp.Models
{
    public class DataCache : IDataCache
    {
        private object syncRoot = new object();
        private IDictionary<int, AlbumM> photos;
        private IDictionary<int, PostM> posts;
        private readonly IAlbumService albumService;
        private readonly IBlogService blogService;

        public DataCache(
            IAlbumService albumService,
            IBlogService blogService)
        {
            this.albumService = albumService;
            this.blogService = blogService;
        }

        public void ReloadDataAlbums()
        {
            lock (syncRoot)
            {
                photos = BuildDictionaryAlbums();
            }
        }

        public void ReloadDataBlog()
        {
            lock (syncRoot)
            {
                posts = BuildDictionaryPosts();
            }
        }

        private IDictionary<int, PostM> BuildDictionaryPosts()
        {
            var postMs = blogService.GetPosts();
            return postMs.ToDictionary(p => p.PostId);
        }

        private IDictionary<int, AlbumM> BuildDictionaryAlbums()
        {
            var albums = albumService.GetAlbums();
            return albums.ToDictionary(p => p.AlbumId);
        }

        public IDictionary<int, AlbumM> GetAlbums()
        {
            lock (syncRoot)
            {
                return photos ?? (photos = BuildDictionaryAlbums());
            }
        }

        public IDictionary<int, PostM> GetPosts()
        {
            lock (syncRoot)
            {
                return posts ?? (posts = BuildDictionaryPosts());
            }
        }
    }
}